package cn.org.xiaosheng.strategy.context;

import cn.org.xiaosheng.enums.OperateTypeEnum;
import cn.org.xiaosheng.strategy.solver.Solver;
import jakarta.annotation.PostConstruct;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

@Component
public class SolverChooser implements ApplicationContextAware {

    private Map<OperateTypeEnum, Solver> chooseMap = new HashMap<OperateTypeEnum, Solver>();

    private ApplicationContext context;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.context = applicationContext;
    }

    public Solver choose(OperateTypeEnum operateTypeEnum) {
        return chooseMap.get(operateTypeEnum);
    }

    /**
     * 在容器初始化时，将所有的Solver都加载到ChooseMap中
     */
    @PostConstruct
    public void init() {
        Map<String, Solver> beans = context.getBeansOfType(Solver.class);
        beans.forEach((name, bean) -> {
            chooseMap.put(bean.supports(), bean);
        });
    }



}
